package com.bxl.chooser.oper.impl;

import com.bxl.chooser.bean.AppInfo;
import com.bxl.chooser.bean.ChooseMsg;
import com.bxl.chooser.bean.ChooseResponseMsg;
import com.bxl.chooser.bean.MessageBean;
import com.bxl.chooser.context.ChooserContext;
import com.bxl.chooser.factory.ChooseMsgFactory;
import com.bxl.chooser.factory.MessageBeanFactory;
import com.bxl.chooser.oper.IOperSv;
import com.bxl.chooser.oper.OperDefine;
import com.bxl.netty.rpc.client.common.client.ClientInfo;
import com.bxl.netty.rpc.common.message.PackageMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 选举服务
 *
 * @author baixl
 * @date 2021/3/25
 */
public class CommitMessageService implements IOperSv<ChooseResponseMsg> {
    private Logger logger = LoggerFactory.getLogger(CommitMessageService.class);

    @Override
    public ChooseResponseMsg oper(PackageMsg<ChooseMsg> msg, ChooserContext context) {
        try {
            AppInfo appInfo = context.getAppInfo();
            if(appInfo.commitMessage(msg.getContent().getCommitLogIndex())){
                return ChooseMsgFactory.createChooseResponseMsg(context.getAppInfo().getTerm(), true);
            }else{
                return ChooseMsgFactory.createChooseResponseMsg(context.getAppInfo().getTerm(), false);
            }
        } catch (Exception e) {
            logger.error("消息写入失败");
        }
        //数据写入失败
        return ChooseMsgFactory.createChooseResponseMsg(context.getAppInfo().getTerm(), false);
    }
}
